package com.tc.quartz.support.quartz;

import com.tc.report.StringUtils;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

/**
 * 调度器Scheduler生成器
 * @author yongjin.ye
 * 
 */
public class VpalSchedulerFactory {
	
	protected static Logger log = LoggerFactory.getLogger(VpalSchedulerFactory.class);
	
	static final String VPAL_PROPERTIES_FILE = "quartz/template.qrtz.properties";//调度器配置文件名称、

	/**
	 * 根据schedulerName，生成相对应的调度器
	 * @param schedulerName
	 * @return
	 * @throws IOException
	 * @throws SchedulerException
	 */
	public synchronized static Scheduler getVpalScheduler(String schedulerName, Map<String, String> quartzDataSourceProperties) throws IOException, SchedulerException{
		if(StringUtils.isBlank(schedulerName)) {
			throw new IllegalArgumentException("创建调度器：schedulerName名称不能为空！");
		}
		InputStream inputStream = null;
		Scheduler scheduler = null;
		try {
			inputStream = VpalSchedulerFactory.class.getClassLoader().getResourceAsStream(VpalSchedulerFactory.VPAL_PROPERTIES_FILE);
			Properties props = new Properties();
			props.load(inputStream);
			props.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, schedulerName);//设置调度器名称
			//设置外部参数
			for (String key : quartzDataSourceProperties.keySet()) {
				props.put(key, quartzDataSourceProperties.get(key));
			}
			StdSchedulerFactory sf = new StdSchedulerFactory();
			sf.initialize(props);
			scheduler = sf.getScheduler();
			//暂停调度任务
			scheduler.standby();
			log.info("当前生成调度器名称:" + scheduler.getSchedulerName());
		} catch (Exception e) {
			log.error("根据schedulerName生成相对应的调度器["+scheduler.getSchedulerName()+"]异常", e);
		}finally{
			if(inputStream != null) {
				inputStream.close();
				inputStream = null;
			}
		}
		return scheduler;
	}
	
	public static void shutdown(Scheduler scheduler) throws Exception {
		try {
			if (null != scheduler) {
				scheduler.shutdown();
				scheduler = null;
			}
		} catch (Exception e) {
			log.error("VpalSchedulerFactory scheduler.shutdown异常", e);
			throw e;
		}
	}

}
